module SpreadsheetToJson
  class SheetToJson
    attr_reader :spreadsheet
  
    def initialize(spreadsheet)
      @spreadsheet = spreadsheet
    end
  
    # Convert the selected rows to json with worksheet id 
    # param rows is an array with row numbers that will be convert to json
    # keys_row_num is the sheet's row number with json keys
    def convert_rows_by_sheet_id(worksheet_id, *rows, keys_row_num)
      rows_to_json(
        spreadsheet.get_sheet_by_id(worksheet_id),
        rows,
        keys_row_num
      )
    end
  
    # Convert the selected rows to json with worksheet name
    def convert_rows_by_sheet_name(worksheet_name, *rows, keys_row_num)
      rows_to_json(
        spreadsheet.get_sheet_by_name(worksheet_name),
        rows,
        keys_row_num
      )
    end
  
    # Convert a total sheet to json by worksheet name
    def convert_a_worksheet_by_name(worksheet_name, keys_row_num) 
      worksheet = spreadsheet.get_sheet_by_name(worksheet_name)
      rows_to_json(
        worksheet,
        [*keys_row_num+1..worksheet.num_rows],
        keys_row_num
      )
    end
  
    # Convert a total sheet to json by worksheet id
    def convert_a_worksheet_by_id(worksheet_id, keys_row_num) 
      worksheet = spreadsheet.get_sheet_by_id(worksheet_id)
      rows_to_json(
        worksheet,
        [*keys_row_num+1..worksheet.num_rows],
        keys_row_num
      )
    end
  
    # Write the json to a file
    def output_json_file(content, output_path)
      unless File.exist?(output_path)
        File.new(output_path, 'w+')
      end
      File.open(output_path, 'w+') {|file| file.write(content) }
    end
  
    private
    # Construct rows to json content
    def rows_to_json(worksheet, *rows, keys_row_num)
      rows.map { |row_num| construct_hash(worksheet, keys_row_num-2, row_num-2) }.to_json
    end
  
    # Construct a hash with one row. param row is the constructed row number
    def construct_hash(worksheet, keys_row_num, row=1)
      if row < 1
        puts "Illeagal row num"
        exit
      end
  
      begin
        json_keys = worksheet.list[keys_row_num].to_hash.values
      rescue NoMethodError
        puts "Worksheet does not exist"
        exit
      end
      json_values = worksheet.list[row].to_hash.values
      Hash[json_keys.zip(json_values)]
    end
  end
end
